<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>broadcastchannel的使用</title>
  <style>
    body{
        background-color: black;
    }
    .box{
        width: 200px; 
        height: 200px; 
        margin: 100px auto;
    }
    .box li button{
        display: block;
        border-radius: 10px;
        background-color: #fff;
        width: 200px;
        height: 50px;
        line-height: 50px;
        text-decoration: none;
        text-align: center;
        margin-top: 50px;
    }
   
  </style>
</head>
<body>
    <ul class="box">
        <li>
            <button name="歌曲1">歌曲1</button>
        </li>
        <li>
            <button  name="歌曲2">歌曲2</button>
        </li>
        <li>
            <button  name="歌曲3">歌曲3</button>
        </li>
    </ul>
    <script>
        const buttons = document.querySelectorAll('button');
        //创建一个mychannel频道。和新打开的页面进行通讯
        const cast = new BroadcastChannel('mychannel'); 

        //用于判断是否打开了新页面，打开了就传过来，这边接受后就不要打开新页面了
        var kai = 'no';
        cast.onmessage = function (e) {
            if(e.data.kai == 'yes')
            {
                kai = 'yes';
            }
        }
        
        //打开页面播放音乐
        for(const b of buttons)
        {
            b.onclick = (e) => {
                if(kai == 'no')
                {
                    window.open('/broadcastchannel2.html?name='+e.target.name);
                }
                //把本次按钮点击的歌曲名称传过去
                data = {name: e.target.name};
                cast.postMessage(data);  
                
            }
        }       
    </script>
</body>
</html>